import React, { useContext, useEffect, useState } from 'react';
import { Button, Col, Empty, Form, Input, List, Modal, Row, Select, Space, Spin, Table, message } from 'antd';
import pageStyles from '@/common/pageLayout.less';
import { arieaEchoRender, getKeyRouter } from '@/utils';
import { history } from 'umi';
import { UploadFormCommon } from '@/components/UploadForm';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { ISupplierActionEnum, SupplierLocaldataContext } from '../common';
import { SelectBankService, addSupplierInfoService, editSupplierInfoService } from '../services';
import { UpdateTableColumns } from '../mconfig';
import Cls from 'classnames';
import _ from 'lodash';
import InfiniteScroll from 'react-infinite-scroller';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
const { confirm } = Modal;

export const UpdateViewLeftForm: React.FC<SupplierManageAPI.IUpdateViewLeftForm> = ({ supplierCollapseKey, collapseChange }) => {
  /**  表单 form */
  const [supplierForm] = Form.useForm();

  /** 获取上下文 */
  const { curRes, locationID, supplierInfoObj, updateFixCls, reloadDetailInfo, supplierDispath, locationProps } = useContext(SupplierLocaldataContext);

  /** 表格数据源 */
  const [tableData, setTableData] = useState<Record<string, any>[]>([{ id: getKeyRouter() }]);

  /** 数据值 */
  const [searchVal, setSearchVal] = useState<string | undefined>();

  /** 开户行select受控模式 */
  const [open, setOpen] = useState(false);

  /** 企业属性标记 */
  const [enterType, setEnterType] = useState(0);

  /**
   * 获取数据
   * */
  const {
    loading: bankLoading,
    getBankRun,
    reloadRefresh,
    data,
    pagination,
  } = SelectBankService((res) => {
    if (res && res?.msgFlag) {
      // setManageDataList(res?.rows);
      setScrollObj({
        ...scrollObj,
        loading: false,
        hasMore: true,
        total: res.total,
      });
    } else {
      message.error(res?.msg);
    }
  });

  /** 保存的分页参数 */
  const [scrollObj, setScrollObj] = useState<any>({
    total: 0,
    count: 1,
    loading: false,
    hasMore: true,
    limit: 10,
  });

  /** 初始化获取数据 */
  const defaultGetWarnData = () => {
    let { count, limit } = scrollObj;
    count++;
    setScrollObj({
      ...scrollObj,
      count: count,
      loading: true,
    });
    let payload: Record<string, any> = {
      current: 1,
      pageSize: count * 10 + limit,
      // bankName: searchVal,
    };
    if (searchVal) {
      payload.bankName = searchVal?.split(' ')?.join(',');
    }
    getBankRun(payload);
  };

  /** 滚动加载 */
  const handleInfiniteOnLoad = () => {
    const { total } = scrollObj;
    if (Number(data?.rows?.length) >= total) {
      message.warning('没有更多数据了！');
      setScrollObj({
        ...scrollObj,
        hasMore: false,
        loading: false,
      });
      return;
    }
    defaultGetWarnData();
  };

  useEffect(() => {
    if (locationID && supplierInfoObj?.id) {
      // 编辑的情况

      let table = supplierInfoObj?.msupplierContacterList?.map((item) => {
        return { fullName: item?.fullName, phoneMobile: item?.phoneMobile };
      });

      if (Array?.isArray(table) && table?.length >= 1) {
        table?.unshift({ fullName: supplierInfoObj?.contactName, phoneMobile: supplierInfoObj?.contactMobile });
      } else {
        table = [{ fullName: supplierInfoObj?.contactName, phoneMobile: supplierInfoObj?.contactMobile }];
      }

      supplierForm?.setFieldsValue({
        ...supplierInfoObj,
        // belongArea: arieaEchoRender(supplierInfoObj), // 区域处理
        table,
      });

      setTableData(table);

      setEnterType(supplierInfoObj?.enterpriseType || 0);
    }
  }, [locationID, supplierInfoObj]);

  /**
   * 添加编辑接口回调
   * @param res 接口返回数据
   * @param updateType 添加或者编辑接口
   */
  const updateSupplierCallback = (res: Record<string, any>, updateType: boolean) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      if (updateType) {
        history.push({
          pathname: `/supplierInfoController/edit/:${getKeyRouter()}${getKeyRouter()}`,
          state: {
            id: res?.obj,
            delRouterName: history.location.pathname, //必传,要删除的路由名称
          },
        });
      } else {
        reloadDetailInfo();
      }
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入添加接口 */
  const { addSupplierInfoRun, addSupplierInfoLoading } = addSupplierInfoService(updateSupplierCallback);

  /** 引入编辑接口 */
  const { editSupplierInfoRun, editSupplierInfoLoading } = editSupplierInfoService(updateSupplierCallback);

  /** 保存供应商信息 */
  const onSaveSupplier = () => {
    supplierForm?.validateFields()?.then((formVal) => {
      // 整合数据
      let payload = {
        ...formVal,
        // provinceCode: formVal?.belongArea && formVal?.belongArea?.length ? formVal?.belongArea?.[0] : null, //省份
        // cityCode: formVal?.belongArea && formVal?.belongArea?.length ? formVal?.belongArea?.[1] : null, //城市
        // countyCode: formVal?.belongArea && formVal?.belongArea?.length ? formVal?.belongArea?.[2] : null, //县城
        contactName: formVal?.table?.[0]?.fullName, //首要联系人姓名
        contactMobile: formVal?.table?.[0]?.phoneMobile, //首要联系人电话
      };

      // 判断table长度，除去第一项是首要联系人，剩下的是添加的
      if (formVal?.table?.length > 1) {
        const newTableData = formVal?.table?.filter((_item, index) => index != 0);
        payload.msupplierContacterList = newTableData;
      } else {
        payload.msupplierContacterList = null;
      }

      // 删除省份数组
      // delete payload['belongArea'];
      // 删除表格数据
      delete payload['table'];

      // 新增 | 编辑
      if (supplierInfoObj?.id) {
        payload.id = supplierInfoObj?.id;
        payload.versionNum = supplierInfoObj?.versionNum;
        editSupplierInfoRun(payload);
      } else {
        addSupplierInfoRun(payload);
      }
    });
  };

  /** 表格内按钮点击方法 */
  const onTableClick = (type, dataIndex) => {
    if (type === 'add') {
      if (typeof tableData === 'undefined') {
        setTableData([{ id: getKeyRouter() }]);
      } else {
        let newtableData = _?.cloneDeep(tableData);
        newtableData?.push({ id: getKeyRouter() });
        setTableData(newtableData);
      }
    } else if (type === 'delete') {
      const tablePropsVal = supplierForm?.getFieldValue('table');
      const tablePropsVals = _?.cloneDeep(tablePropsVal);
      tablePropsVals?.splice(dataIndex, 1);
      supplierForm?.setFieldsValue({
        table: tablePropsVals,
      });
      if (typeof tablePropsVal === 'undefined') {
        setTableData([{ id: getKeyRouter() }]);
      } else {
        setTableData(tablePropsVals);
      }
    }
  };

  return (
    <Spin spinning={addSupplierInfoLoading || editSupplierInfoLoading}>
      <div className={'commonTabsBodyDom'}>
        <div className="tabsBodyInfoDom">
          <ScrollBarLayout>
            <div className={Cls(pageStyles['fromView-styles'], `${updateFixCls}supplierFormLabel`)}>
              <Form form={supplierForm}>
                <div className={`${updateFixCls}supplierFormLabel-formBoxRoot`}>
                  <div className={`${updateFixCls}supplierFormLabel-minBoxTitle`}>单位信息</div>
                  <Row>
                    <Col span={12}>
                      <Form.Item
                        label="单位名称"
                        name="fullName"
                        rules={[
                          {
                            required: true,
                            message: '请输入单位名称',
                          },
                        ]}
                      >
                        <Input
                          placeholder="请输入"
                          allowClear
                          onChange={(e: any) => {
                            if (e?.target?.value) {
                              supplierDispath({
                                type: ISupplierActionEnum.SUPPLIER_NAME,
                                payload: e?.target?.value,
                              });
                            }
                          }}
                        />
                      </Form.Item>
                    </Col>

                    <Col span={12}>
                      {/* <Form.Item label="单位简称" name="shortName">
                        <Input placeholder="请输入" allowClear />
                      </Form.Item> */}
                      <TagSelect
                        formLabel="企业属性"
                        formName="enterpriseType"
                        formRequired={true}
                        radioList={[
                          {
                            value: 0,
                            name: '大陆',
                          },
                          {
                            value: 1,
                            name: '港澳台',
                          },
                          {
                            value: 2,
                            name: '境外',
                          },
                        ]}
                        defalultKeys={supplierInfoObj?.enterpriseType || 0}
                        onChange={(valNum) => {
                          setEnterType(valNum);
                          if (valNum) {
                            supplierForm?.validateFields();
                          }
                        }}
                      />
                    </Col>

                    <Col span={12}>
                      <Form.Item
                        label="法定代表人"
                        name="legalName"
                        rules={
                          enterType
                            ? undefined
                            : [
                                {
                                  required: true,
                                  message: '请输入法定代表人',
                                },
                              ]
                        }
                      >
                        <Input placeholder="请输入" allowClear />
                      </Form.Item>
                    </Col>

                    <Col span={12}>
                      <Form.Item label="所属区域" name="registerAddress">
                        <Input placeholder="请输入" allowClear />
                      </Form.Item>
                    </Col>

                    <Col span={12}>
                      <Form.Item
                        label={enterType ? '企业注册代码' : '统一社会信用代码'}
                        name="creditID"
                        rules={
                          enterType
                            ? undefined
                            : [
                                {
                                  required: true,
                                  message: '请输入' + (enterType ? '企业注册代码' : '统一社会信用代码'),
                                },
                              ]
                        }
                      >
                        <Input placeholder="请输入" allowClear />
                      </Form.Item>
                    </Col>

                    <Col span={12}>
                      <Form.Item
                        label="注册电话"
                        name="registerPhone"
                        rules={
                          enterType
                            ? undefined
                            : [
                                {
                                  required: true,
                                  message: '请输入注册电话',
                                },
                              ]
                        }
                      >
                        <Input placeholder="请输入" allowClear />
                      </Form.Item>
                    </Col>

                    <Col span={12}>
                      <Form.Item
                        label="开户行名称"
                        name="bankName"
                        rules={
                          enterType
                            ? undefined
                            : [
                                {
                                  required: true,
                                  message: '请选择开户行',
                                },
                              ]
                        }
                      >
                        <Select
                          open={open}
                          onDropdownVisibleChange={(visible) => setOpen(visible)}
                          allowClear
                          showSearch
                          onSearch={_?.debounce((val) => {
                            if (val) {
                              setSearchVal(val);
                              getBankRun({ current: 1, pageSize: 10, bankName: val?.split(' ')?.join(',') });
                              setScrollObj({
                                ...scrollObj,
                                count: 1,
                              });
                            } else {
                              setSearchVal(undefined);
                              getBankRun({ current: 1, pageSize: 10 });
                              setScrollObj({
                                ...scrollObj,
                                count: 1,
                              });
                            }
                          }, 1000)}
                          onClear={() => {
                            supplierForm?.setFieldValue('bankCode', undefined);
                            getBankRun({ current: 1, pageSize: 10 });
                            setScrollObj({
                              ...scrollObj,
                              count: 1,
                            });
                          }}
                          onSelect={(val, node) => supplierForm?.setFieldValue('bankCode', node?.key)}
                          filterOption={false}
                          placeholder={'请选择（多关键字用空格隔开）'}
                          dropdownRender={(menu) => (
                            <div className={'bankSelectScrollBox'} style={{ width: '100%', height: '300px' }}>
                              <InfiniteScroll
                                loadMore={handleInfiniteOnLoad}
                                initialLoad={false}
                                pageStart={1}
                                useWindow={false}
                                hasMore={!scrollObj?.loading && scrollObj?.hasMore}
                                loader={
                                  scrollObj?.loading ? (
                                    <div style={{ textAlign: 'center' }}>
                                      <Spin size="small" />
                                    </div>
                                  ) : (
                                    <></>
                                  )
                                }
                              >
                                <div className="commonTabsBodyDom">
                                  {data?.rows?.length ? (
                                    <div style={{ padding: '0px 5px', cursor: 'pointer' }}>
                                      <List
                                        itemLayout="horizontal"
                                        size="small"
                                        dataSource={data?.rows}
                                        renderItem={(item: Record<string, any>) => {
                                          return (
                                            <List.Item
                                              onClick={() => {
                                                supplierForm?.setFieldsValue({
                                                  bankName: item?.bankName,
                                                  bankCode: item?.bankCode,
                                                });
                                                setOpen(false);
                                              }}
                                            >
                                              <List.Item.Meta title={item?.bankName} />
                                            </List.Item>
                                          );
                                        }}
                                      />
                                    </div>
                                  ) : (
                                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />
                                  )}
                                </div>
                              </InfiniteScroll>
                            </div>
                          )}
                        ></Select>
                      </Form.Item>
                    </Col>

                    <Col span={12}>
                      <Form.Item
                        label="开户行账号"
                        name="bankAccount"
                        rules={
                          enterType
                            ? undefined
                            : [
                                {
                                  required: true,
                                  message: '请输入开户行账号',
                                },
                              ]
                        }
                      >
                        <Input placeholder="请输入" allowClear />
                      </Form.Item>
                    </Col>

                    <Col span={12}>
                      <Form.Item
                        label="银行行号"
                        name="bankCode"
                        // rules={[
                        //   {
                        //     required: true,
                        //     message: '请选择开户行',
                        //   },
                        // ]}
                      >
                        <Input placeholder="自动带出" disabled />
                      </Form.Item>
                    </Col>

                    <Col span={12}>
                      <Form.Item
                        label="单位地址"
                        name="workAddress"
                        rules={
                          enterType
                            ? undefined
                            : [
                                {
                                  required: true,
                                  message: '请选择单位地址',
                                },
                              ]
                        }
                      >
                        <Input placeholder="请输入" allowClear />
                      </Form.Item>
                    </Col>

                    <UploadFormCommon
                      form={supplierForm}
                      fileFormName={'licenceURL'}
                      spanCol={24}
                      inRowProportion={24}
                      name={'attachFile'}
                      url={'/supplierInfoController/uploadFile'}
                      downloadUrl={'/supplierInfoController/downloadFile'}
                      label="营业执照"
                      required={false}
                      accept={'.jpg|.png|.jpeg'}
                      fileFormDelName={'licenceURLDel'}
                      delFunc={() => {}}
                      maxFile={1}
                      fieldBusiPath={'supplier/info'}
                      defaultFiles={supplierInfoObj && supplierInfoObj?.licenceURL ? supplierInfoObj?.licenceURL : null}
                    >
                      营业执照
                    </UploadFormCommon>
                  </Row>
                  <div className={`${updateFixCls}supplierFormLabel-minBoxTitle`}>联系人信息</div>
                  <div className="list-table">
                    <Form.Item name="table" valuePropName="tableData">
                      <Table bordered size={'small'} pagination={false} dataSource={tableData} columns={UpdateTableColumns(onTableClick, enterType)} />
                    </Form.Item>
                  </div>
                </div>
              </Form>
            </div>
          </ScrollBarLayout>
        </div>
        <div className="tabsBodyBottomBtn">
          <Space>
            {((supplierInfoObj?.id && curRes['/supplierInfoController/edit']) || (!supplierInfoObj?.id && curRes['/supplierInfoController/add'])) && (
              <Button type={'primary'} onClick={onSaveSupplier}>
                保存
              </Button>
            )}

            <Button
              danger
              onClick={() => {
                confirm({
                  title: '关闭',
                  icon: <QuestionCircleOutlined />,
                  content: '确定要关闭当前页吗？',
                  okText: '确定',
                  okType: 'primary',
                  cancelText: '取消',
                  centered: true,
                  onOk() {
                    history.push({
                      pathname: locationProps?.state?.returnPathName,
                      state: {
                        delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
                        returnPathName: locationProps?.state?.returnPathName,
                      },
                    });
                  },
                  onCancel() {},
                });
              }}
            >
              关闭
            </Button>
          </Space>
        </div>
      </div>
    </Spin>
  );
};
